package org.light.domain;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.light.core.DotClassPathXml;
import org.light.core.DotProjectXml;
import org.light.core.LayoutComb;
import org.light.core.Log4jProperties;
import org.light.core.ReportComb;
import org.light.core.SettingEclipseJdtPrefs;
import org.light.core.SettingEclipsePrefs;
import org.light.core.SettingEclipseSuperTypeContainer;
import org.light.core.SettingEclipseSuperTypeName;
import org.light.core.SettingEclipseWstFacetXml;
import org.light.core.SettingJsdtScopeXml;
import org.light.core.SettingWstComponentXml;
import org.light.core.WebXml;
import org.light.easyuilayouts.EasyUIMtmPI;
import org.light.easyuilayouts.widgets.Nav;
import org.light.exception.ValidateException;
import org.light.generator.DBDefinitionGenerator;
import org.light.generator.DateUtilGenerator;
import org.light.generator.ImageUtilGenerator;
import org.light.generator.JsonDateValueProcessorGenerator;
import org.light.generator.JsonImageValueProcessorGenerator;
import org.light.generator.JumpHomepageGenerator;
import org.light.generator.MSExcelUtilGenerator;
import org.light.generator.PDFUtilGenerator;
import org.light.generator.POIExcelUtilGenerator;
import org.light.generator.POIPPTUtilGenerator;
import org.light.generator.POMXml;
import org.light.generator.TwoDomainsDBDefinitionGenerator;
import org.light.generator.WordUtilGenerator;
import org.light.layouts.EasyUIHomePagePI;
import org.light.oracle.generator.Oracle11gSqlReflector;
import org.light.oracle.generator.OracleTwoDomainsDBDefinitionGenerator;
import org.light.simpleauth.AuthJsGenerator;
import org.light.simpleauth.CorsFilterGenerator;
import org.light.simpleauth.LoginFilterGenerator;
import org.light.simpleauth.SimpleAuthModule;
import org.light.utils.BooleanUtilGenerator;
import org.light.utils.ConfigParser;
import org.light.utils.DBConf;
import org.light.utils.DbconfigXml;
import org.light.utils.EncodingFilter;
import org.light.utils.ParseXML;
import org.light.utils.PgsqlReflector;
import org.light.utils.ReadConfigXml;
import org.light.utils.SqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.StringUtilGenerator;
import org.light.utils.TypeUtil;
import org.light.utils.ZipCompressor;
import org.light.wizard.ExcelWizard;

public class Project {
	protected long projectId;
	protected String standardName;
	protected String packageToken;
	protected String technicalstack;
	protected String folderPath = "D:/JerryWork/Infinity/testFiles/";
	protected String sourceFolderPath = "D:/JerryLunaWorkspace/InfinityGPGenerator/WebContent/templates/";
	protected String moduleSourceFolderPath = "D:/JerryLunaWorkspace/InfinityGPGenerator/WebContent/moduletemplates/";
	protected List<Prism> prisms = new ArrayList<Prism>();
	protected List<Util> utils = new ArrayList<Util>();
	protected List<DBUtil> dbUtils = new ArrayList<DBUtil>();
	protected List<SrcRootUtil> srcRootUtils = new ArrayList<SrcRootUtil>();
	protected List<DBDefinitionGenerator> dbDefinitionGenerators = new ArrayList<DBDefinitionGenerator>();
	protected String dbName;
	protected TestSuite projectTestSuite = new TestSuite();
	protected List<ConfigFile> configFiles = new ArrayList<ConfigFile>();
	protected List<Domain> domains = new ArrayList<Domain>();
	protected String dbPrefix = "";
	protected String dbUsername = "root";
	protected String dbPassword = "";
	protected String dbType="mysql";
	protected boolean emptypassword = false;
	protected String sgsSource;
	protected String sqlSource;
	protected String label;
	protected List<List<Domain>> dataDomains = new ArrayList<>();
	protected String excelTemplateName = "";
	protected String excelTemplateFolder = "";
	protected String title = "";
	protected String subTitle = "";
	protected String footer = "";
	protected String crossOrigin = "";
	protected String resolution = "high";
	protected String domainSuffix = "domain";
	protected String daoSuffix = "dao";
	protected String daoimplSuffix = "daoimpl";
	protected String serviceSuffix = "service";
	protected String serviceimplSuffix = "serviceimpl";
	protected String controllerSuffix = "controller";
	protected String domainNamingSuffix = "";
	protected String controllerNamingSuffix = "Controller";
	protected String language = "chinese";
	protected String schema = "normal";
	protected String frontBaseApi = "";
	protected List<org.light.core.Module> modules = new ArrayList<>();
	protected List<LayoutComb> layoutCombs = new ArrayList<>();
	protected List<ReportComb> reportCombs = new ArrayList<>();
	protected Nav nav;
	protected boolean sqlCommentsOn = false;
	protected String computerLanguage = "java";
	protected String originalExcelTemplateName;
	protected String frontendUi = "vueElNode21";
	protected String backendUi = "easyUi";
	protected List<TwoDomainsDBDefinitionGenerator> myTwoDBGenerators = new ArrayList<TwoDomainsDBDefinitionGenerator>();
	protected Boolean withAuth = false;
	protected List<Filter> filters = new ArrayList<Filter>();
	protected List<ManyToManyCandidate> mtmCandidates = new ArrayList<>();
	protected List<List<ManyToManyCandidate>> mtmCandidatesValues = new ArrayList<>();

	public List<List<ManyToManyCandidate>> getMtmCandidatesValues() {
		return mtmCandidatesValues;
	}

	public void setMtmCandidatesValues(List<List<ManyToManyCandidate>> mtmCandidatesValues) {
		this.mtmCandidatesValues = mtmCandidatesValues;
	}
	
	public void addMtmCandidateValues(List<ManyToManyCandidate> mtmCandidatesValues) {
		this.mtmCandidatesValues.add(mtmCandidatesValues);
	}

	public List<ManyToManyCandidate> getMtmCandidates() {
		return mtmCandidates;
	}

	public void setMtmCandidates(List<ManyToManyCandidate> mtmCandidates) {
		this.mtmCandidates = mtmCandidates;
	}

	public void addMtmCandidate(ManyToManyCandidate mtmc) {
		this.mtmCandidates.add(mtmc);
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getSubTitle() {
		return subTitle;
	}

	public void setSubTitle(String subTitle) {
		this.subTitle = subTitle;
	}

	public String getFooter() {
		return footer;
	}

	public void setFooter(String footer) {
		this.footer = footer;
	}

	public String getCrossOrigin() {
		return crossOrigin;
	}

	public void setCrossOrigin(String crossOrigin) {
		this.crossOrigin = crossOrigin;
	}

	public void setResolution(String resolution) {
		this.resolution = resolution;
	}
	
	public String getResolution() {
		return resolution;
	}

	public List<Filter> getFilters() {
		return filters;
	}

	public void setFilters(List<Filter> filters) {
		this.filters = filters;
	}
	
	public void addFilter(Filter filter) {
		this.filters.add(filter);
	}

	public String getSgsSource() {
		return sgsSource;
	}

	public void setSgsSource(String sgsSource) {
		this.sgsSource = sgsSource;
	}

	public String getSqlSource() {
		return sqlSource;
	}

	public void setSqlSource(String sqlSource) {
		this.sqlSource = sqlSource;
	}
	
	public boolean isEmptypassword() {
		return emptypassword;
	}

	public void setEmptypassword(boolean emptypassword) {
		this.emptypassword = emptypassword;
	}

	public Project(){
		super();
	}
	
	public void decorateProject() throws ValidateException{
		addDBUtil(new DBConf(packageToken));
		addDBUtil(new ConfigParser(packageToken));
		addDBUtil(new ParseXML(packageToken));
		addDBUtil(new ReadConfigXml(packageToken));
		addSrcRootUtil(new DbconfigXml(this.getDbName(),this.getDbUsername(),this.getDbPassword(),emptypassword));
		EncodingFilter eFilter = new EncodingFilter(packageToken);
		addFilter(eFilter);
		WebXml webxml = new WebXml();
		webxml.setPackageToken(packageToken);
		webxml.setProjectName(this.getStandardName());
		webxml.addFilter(eFilter);
		addConfigFile(webxml);
		
		Log4jProperties log4j = new Log4jProperties();
		log4j.setPutInsideSrcAndClasses(true);
		addConfigFile(log4j);
		
		DotProjectXml dpxml = new DotProjectXml();
		dpxml.setProjectName(this.standardName);
		addConfigFile(dpxml);
		
		DotClassPathXml dcpxml = new DotClassPathXml();
		addConfigFile(dcpxml);
		
		SettingJsdtScopeXml sscopexml = new SettingJsdtScopeXml();
		addConfigFile(sscopexml);
		
		SettingEclipseJdtPrefs sejPrefs = new SettingEclipseJdtPrefs();
		addConfigFile(sejPrefs);
		
		SettingEclipsePrefs sePrefs = new SettingEclipsePrefs();
		addConfigFile(sePrefs);
		
		SettingEclipseSuperTypeContainer sContainer = new SettingEclipseSuperTypeContainer();
		addConfigFile(sContainer);
		
		SettingEclipseSuperTypeName sSuperTypeName = new  SettingEclipseSuperTypeName();
		addConfigFile(sSuperTypeName);
		
		SettingEclipseWstFacetXml sFacetXml = new SettingEclipseWstFacetXml();
		addConfigFile(sFacetXml);
		
		SettingWstComponentXml sComponentXml = new SettingWstComponentXml();
		sComponentXml.setProjectName(this.standardName);
		addConfigFile(sComponentXml);
				
		addUtil(new BooleanUtilGenerator(packageToken));
		addUtil(new StringUtilGenerator(packageToken));
		addUtil(new POIExcelUtilGenerator(packageToken));
		addUtil(new PDFUtilGenerator(packageToken));
		addUtil(new POIPPTUtilGenerator(packageToken));
		addUtil(new WordUtilGenerator(packageToken));
		addUtil(new MSExcelUtilGenerator(packageToken));
	}
	
	public ConfigFile findConfigFile(String standardName){
		if (this.configFiles != null && this.configFiles.size()>0){
			for (ConfigFile c : this.configFiles){
				if (c.getStandardName().equals(standardName)) return c;
			}
		}
		return null;
	}
	
	public List<Util> getUtils() {
		return utils;
	}
	public void setUtils(List<Util> utils) {
		this.utils = utils;
	}
	
	public void addUtil(Util util){
		this.utils.add(util);
	}
	
	public List<DBUtil> getDBUtils() {
		return this.dbUtils;
	}
	public void setDBUtils(List<DBUtil> dbUtils) {
		this.dbUtils = dbUtils;
	}
	
	public void addDBUtil(DBUtil dbUtil){
		this.dbUtils.add(dbUtil);
	}
	
	public List<SrcRootUtil> getSrcRootUtils() {
		return this.srcRootUtils;
	}
	
	public void setSrcRootUtils(List<SrcRootUtil> srcRootUtils) {
		this.srcRootUtils = srcRootUtils;
	}
	
	public void addSrcRootUtil(SrcRootUtil srcRootUtils){
		this.srcRootUtils.add(srcRootUtils);
	}

	public long getProjectId() {
		return projectId;
	}
	public void setProjectId(long projectId) {
		this.projectId = projectId;
	}
	public String getStandardName() {
		return standardName;
	}
	public void setStandardName(String standardName) {
		this.standardName = standardName;
		WebXml webxml = (WebXml)findConfigFile("web.xml");
		if (webxml != null)
			webxml.setProjectName(standardName);
	}
	public List<Prism> getPrisms() {
		return prisms;
	}
	
	public void addPrism(Prism prism){	
		if (this.technicalstack == null || "".equals(this.technicalstack) ||"jeeeu".equalsIgnoreCase(this.technicalstack)){
			if (this.packageToken != null) prism.setPackageToken(this.packageToken);
			this.prisms.add(prism);
			if (prism.getDbDefinitionGenerator() != null){
				this.dbDefinitionGenerators.add(prism.getDbDefinitionGenerator());
			}
			WebXml webxml = (WebXml)this.findConfigFile("web.xml");
		} 
	}
	public String getPackageToken() {
		return packageToken;
	}
	public void setPackageToken(String packageToken) {
		this.packageToken = packageToken;
		for (Util u: this.utils){
			u.setPackageToken(packageToken);
		}
		WebXml webxml = (WebXml)findConfigFile("web.xml");
		if (webxml != null)
			webxml.setPackageToken(packageToken);
	}
	
	public void generateProjectFiles(Boolean ignoreWarning, Boolean genFormatted, Boolean genUi, Boolean genController,
			Boolean genService, Boolean genServiceImpl, Boolean genDao, Boolean genDaoImpl,Boolean generateExcel, String exportStr) throws ValidateException{
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		ValidateInfo info = this.validate();
		if (info.success(true) == false) {
			for (String s:info.getCompileErrors()){
				System.out.println(s);
			}
			throw new ValidateException(info);
		}
		try {
			decorateMentuItems();
			decorateProject();
			for (Prism ps: this.prisms){
				if (StringUtil.isBlank(exportStr) || exports.contains(ps.getDomain().getStandardName())){
					ps.setFolderPath(this.getProjectFolderPath());
					ps.generatePrismFiles(ignoreWarning, genUi, genController, genService, genServiceImpl, genDao,
							genDaoImpl);
				}
			}

			for (Util u:utils){
				String utilPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(u.getPackageToken()+".utils");
				String utilFilePath = utilPath+u.getFileName();
				writeToFile(utilFilePath, u.generateUtilString());
			}
			
			for (DBUtil du:dbUtils){
				String utilPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(du.getPackageToken()+".database");
				String utilFilePath = utilPath+du.getFileName();
				writeToFile(utilFilePath, du.generateUtilString());
			}
			
			for (SrcRootUtil sru:srcRootUtils){
				String utilPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sru.getPackageToken());
				String utilFilePath = utilPath+sru.getFileName();
				writeToFile(utilFilePath, sru.generateUtilString());
			}
			
			for (Filter ft:filters){
				String ftPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(ft.getPackageToken())+"/filter/";
				String ftFilePath = ftPath+ft.getFileName();
				writeToFile(ftFilePath,ft.generateUtilString());
			}

			AuthJsGenerator authjs = new AuthJsGenerator();
			for (org.light.core.Module m : this.modules) {
				if (StringUtil.isBlank(exportStr) || exports.contains(m.getStandardName())){
					//m.generateModuleFiles(this.getProjectFolderPath(),  genUi, genController,
					//		genService, genServiceImpl, genDao, genDaoImpl);
					m.generateModuleFiles(this.getProjectFolderPath(),  true, true,
					true, true, true, true);
					SimpleAuthModule sam = (SimpleAuthModule) m;
					authjs.setContainsAuth(true);
					authjs.setUserDomain(sam.getUserDomain());
				}
			}
			writeToFile(this.getProjectFolderPath() + "WebContent/js/"+authjs.getFileName(), authjs.generateStatementList().getContent());
			
			
			for (LayoutComb lcb : this.layoutCombs) {
				if (StringUtil.isBlank(exportStr) || exports.contains(lcb.getStandardName())){
					lcb.generateCombFiles(this.getProjectFolderPath());
				}
			}
			
			for (ReportComb rcb : this.reportCombs) {
				if (StringUtil.isBlank(exportStr) || exports.contains(rcb.getStandardName())){
					rcb.generateCombFiles(this.getProjectFolderPath());
				}
			}

			Domain sampleDomain = this.getDomains().get(0);
			
			CorsFilterGenerator corsfg = new CorsFilterGenerator(sampleDomain);
			String corsfgPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/filter/";
			String corsfgFilePath = corsfgPath+corsfg.getFileName();
			writeToFile(corsfgFilePath,corsfg.generateStatementList().getContent());
			
			if (this.containsAuth()){
				for (org.light.core.Module m : this.modules) {
					SimpleAuthModule sam = (SimpleAuthModule) m;
					LoginFilterGenerator lfg = new LoginFilterGenerator();
					lfg.setUserDomain(sam.getUserDomain());
					lfg.setRoleDomain(sam.getRoleDomain());
					lfg.setPrivilegeDomain(sam.getPrivilegeDomain());
					lfg.setDomains(this.getDomains());
					Set<ManyToMany> mtms = new TreeSet<>();
					for (Prism p:this.getPrisms()){
						mtms.addAll(p.getManyToManies());
					}
					lfg.setMtms(mtms);
					lfg.setLayouts(this.getLayoutCombs());
					lfg.setReports(this.getReportCombs());
					String lfgPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/filter/";
					String lfgFilePath = lfgPath+lfg.getFileName();
					writeToFile(lfgFilePath,lfg.generateStatementList().getContent());
				}
			}

			EasyUIHomePagePI homepage = new EasyUIHomePagePI(sampleDomain.getLanguage());
			homepage.setTitles(this.getTitle(),this.getSubTitle(),this.getFooter());
			homepage.setNav(this.getNav());
			homepage.generatePIFiles(this.getProjectFolderPath());

			POMXml pomxml = new POMXml();
			pomxml.setSampleDomain(sampleDomain);
			pomxml.setContainsAuth(this.containsAuth());
			String pomFilePath = this.getProjectFolderPath() +pomxml.getFileName();
			writeToFile(pomFilePath,pomxml.generateStatementList().getContent());

			DateUtilGenerator dug = new DateUtilGenerator();
			dug.setSampleDomain(sampleDomain);
			String dugPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
			String dugFilePath = dugPath+dug.getFileName();
			writeToFile(dugFilePath,dug.generateStatementList().getContent());

			JsonDateValueProcessorGenerator jdpg = new JsonDateValueProcessorGenerator();
			jdpg.setSampleDomain(sampleDomain);
			String jdpgPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
			String jdpgFilePath = jdpgPath+jdpg.getFileName();
			writeToFile(jdpgFilePath,jdpg.generateStatementList().getContent());

			JsonImageValueProcessorGenerator jipg = new JsonImageValueProcessorGenerator();
			jipg.setSampleDomain(sampleDomain);
			String jipgPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
			String jipgFilePath = jipgPath+jipg.getFileName();
			writeToFile(jipgFilePath,jipg.generateStatementList().getContent());

			ImageUtilGenerator iug = new ImageUtilGenerator();
			iug.setSampleDomain(sampleDomain);
			String iugPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
			String iugFilePath = iugPath+iug.getFileName();
			writeToFile(iugFilePath,iug.generateStatementList().getContent());

			JumpHomepageGenerator jhg = new JumpHomepageGenerator();
			jhg.setContainsAuth(this.containsAuth());
			String jhgPath = this.getProjectFolderPath() + "WebContent/";
			String jhgFilePath = jhgPath+jhg.getFileName();
			writeToFile(jhgFilePath,jhg.generateStatementList().getContent());

			//File libto = new File(this.getProjectFolderPath() + "WebContent/WEB-INF/lib/");
			//File libfrom = new File(this.getSourceFolderPath() + "lib/");
			
			FileCopyer copy = new FileCopyer();
			// 设置来源去向
			//copy.dirFrom = libfrom;
			//copy.dirTo = libto;
			//copy.listFileInDir(libfrom);
			
			File cssfrom = new File(this.getSourceFolderPath() + "css/");
			File cssto = new File(this.getProjectFolderPath() + "WebContent/css/");
			
			copy.dirFrom = cssfrom;
			copy.dirTo = cssto;
			copy.listFileInDir(cssfrom);
			
			File jsfrom = new File(this.getSourceFolderPath() + "js/");
			File jsto = new File(this.getProjectFolderPath() + "WebContent/js/");
			
			copy.dirFrom = jsfrom;
			copy.dirTo = jsto;
			copy.listFileInDir(jsfrom);
			
			File easyuifrom = new File(this.getSourceFolderPath() + "easyui/");
			File easyuito = new File(this.getProjectFolderPath() + "WebContent/easyui/");

			copy.dirFrom = easyuifrom;
			copy.dirTo = easyuito;
			copy.listFileInDir(easyuifrom);

			File uploadjsfrom = new File(this.getSourceFolderPath() + "uploadjs/");
			File uploadjsto = new File(this.getProjectFolderPath() + "WebContent/uploadjs/");

			copy.dirFrom = uploadjsfrom;
			copy.dirTo = uploadjsto;
			copy.listFileInDir(uploadjsfrom);

			File imagefrom = new File(this.getSourceFolderPath() + "images/");
			File imageto = new File(this.getProjectFolderPath() + "WebContent/images/");

			copy.dirFrom = imagefrom;
			copy.dirTo = imageto;
			copy.listFileInDir(imagefrom);
			
			File echartsfrom = new File(this.getSourceFolderPath() + "echarts/");
			File echartsto = new File(this.getProjectFolderPath() + "WebContent/echarts/");

			copy.dirFrom = echartsfrom;
			copy.dirTo = echartsto;
			copy.listFileInDir(echartsfrom);
			
			StringBuilder sql = new StringBuilder();			
			boolean createNew = true;
			for (DBDefinitionGenerator dbd:dbDefinitionGenerators){
				sql.append(dbd.generateDBSql(createNew,this.sqlCommentsOn,exportStr)).append("\n");
				if (createNew) createNew = false;
	        }
			
			for (TwoDomainsDBDefinitionGenerator mtg : this.myTwoDBGenerators) {
				sql.append(mtg.generateDBSql(this.getDbType(),this.sqlCommentsOn,exportStr));
			}
			
			for (List<Domain> dataDomains : this.getDataDomains()) {
				sql.append("\n");
				for (Domain d : dataDomains) {
					if (StringUtil.isBlank(exportStr) || exports.contains(d.getStandardName())){
						if (!(d instanceof org.light.domain.Enum)) {
							sql.append(SqlReflector.generateInsertSqlWithValue(d)).append("\n");
						}
					}
				}

				for (Domain d : dataDomains) {
					if (StringUtil.isBlank(exportStr) || exports.contains(d.getStandardName())){
						for (ManyToMany mtm : d.getManyToManies()) {
							sql.append(SqlReflector.generateMtmInsertSqlWithValues(mtm)).append("\n");
						}
					}
				}
			}
						
			String fPath = this.getProjectFolderPath()+"sql/"+this.dbName+".sql";
			writeToFile(fPath,sql.toString());
			
			if (this.getSgsSource()!= null && !this.getSgsSource().equals("")){
				String myfPath = this.getProjectFolderPath()+"sgs/"+this.getStandardName()+"_original.sgs";
				writeToFile(myfPath,this.getSgsSource());
				if (generateExcel) {
					String genExcelFile = this.getStandardName() + ".xls";
					File f = new File((this.getProjectFolderPath()+ "exceltemplate/"+genExcelFile).replace("\\", "/"));
					if (!f.getParentFile().exists()){
						f.getParentFile().mkdirs();
					}
					if (!f.exists()){
						f.createNewFile();
					}
					ExcelWizard.outputExcelWorkBook(this, (this.getProjectFolderPath()+ "exceltemplate/").replace("\\", "/"),genExcelFile);
				}
			}
			
			if (!StringUtil.isBlank(this.getExcelTemplateName())){				
				File mF1 = new File((this.getExcelTemplateFolder()+this.getExcelTemplateName()).replace("\\", "/"));
				File mF2 = new File((this.getProjectFolderPath() + "exceltemplate/"+this.getExcelTemplateName()).replace("\\", "/"));
				if (mF1.exists()){
					if (!mF2.getParentFile().exists()){
						mF2.getParentFile().mkdirs();
					}
					if (!mF2.exists()){
						mF2.createNewFile();
					}
					copy.copy(mF1.getPath(), mF2.getPath());
				}
			}
			
	        for (ConfigFile cf : this.configFiles){
	        	if (cf.isTopLevel()){
	        		String myfPath0 = this.getProjectFolderPath()+cf.getStandardName();
	        		writeToFile(myfPath0, cf.generateConfigFileString());
	        	}else if (cf.isSettingParamFile()){
	        		String myfPath1 = this.getProjectFolderPath()+".settings/"+cf.getStandardName();
	        		writeToFile(myfPath1, cf.generateConfigFileString());
	        	}else if (cf.isPutInsideSrcAndClasses == false){
		        	String myfPath2 = this.getProjectFolderPath()+"WebContent/WEB-INF/"+cf.getStandardName();
		    		writeToFile(myfPath2, cf.generateConfigFileString());
	        	} else {
	        		String myfPath3 = this.getProjectFolderPath()+"src/"+cf.getStandardName();
	        		writeToFile(myfPath3, cf.generateConfigFileString());
		    		
		    		String myfPath4 = this.getProjectFolderPath()+"WebContent/WEB-INF/classes/"+cf.getStandardName();
		    		writeToFile(myfPath4, cf.generateConfigFileString());
	        	}
	        }
		} catch (Exception e){
			e.printStackTrace();
			throw new ValidateException("源码生成错误");
		}
	}
	
	public static String generateMtmInsertSqlWithValues(ManyToMany mtm) throws Exception{
		if (StringUtil.isBlank(mtm.getValues())||mtm.getSlave().isLegacy()) return "";
		else {
		String [] slaveValues = mtm.getValues().split(",");
			String result = "";
				for (String slaveValue:slaveValues) {
				    result = result + "insert into " +  mtm.getMaster().getDbPrefix() + StringUtil.changeDomainFieldtoTableColum(mtm.getMaster().getStandardName()+StringUtil.capFirst(mtm.getSlaveAlias())) +" ";
					result = result + "("+StringUtil.changeDomainFieldtoTableColum(mtm.getMaster().getStandardName()+"Id")+" , "+StringUtil.changeDomainFieldtoTableColum(mtm.getSlaveAlias()+"Id")+") values ( ";		
			        if (TypeUtil.isNumeric(mtm.getMaster().getDomainId().getFieldRawType())){
			        	result = result + mtm.getMaster().getDomainId().getFieldValue() + "," ;
			        }else {
			        	result = result +"'"+ mtm.getMaster().getDomainId().getFieldValue() + "',"; 
			        }
			        if (TypeUtil.isNumeric(mtm.getSlave().getDomainId().getFieldRawType())){
			        	result = result + slaveValue ;
			        }else {
			        	result = result +"'"+ slaveValue + "'"; 
			        }
			        result += ");\n";
				} 
			return result;
		}
	}
		
	public void writeToFile(String filePath, String content) throws Exception{
		File f = new File(filePath);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.createNewFile();
		try (Writer fw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(f.getAbsolutePath()),"UTF-8"))){			
	        fw.write(content,0,content.length());
		}
	}
	
	public String getSourceFolderPath() {
		return sourceFolderPath;
	}

	public void setSourceFolderPath(String sourceFolderPath) {
		this.sourceFolderPath = sourceFolderPath;
	}

	public void generateProjectZip(Boolean ignoreWarning, Boolean genFormatted, Boolean genUi, Boolean genController,
			Boolean genService, Boolean genServiceImpl, Boolean genDao, Boolean genDaoImpl, Boolean generateExcel, String exportStr) throws Exception{
		delAllFile(this.folderPath+this.standardName+".zip");
		delFolder(this.getProjectFolderPath());
		File f = new File(this.getProjectFolderPath());
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		if ("DBTools".equalsIgnoreCase(this.getSchema())) {
			if ("mariadb".equalsIgnoreCase(this.getDbType())||"mysql".equalsIgnoreCase(this.getDbType())) {
				generateMariaDBToolsFiles(genFormatted,exportStr);
			}else if ("oracle".equalsIgnoreCase(this.getDbType())) {
				generateOracleDBToolsFiles(genFormatted,exportStr);
			} else if ("postgresql".equalsIgnoreCase(this.getDbType())||"pgsql".equalsIgnoreCase(this.getDbType())) {
				generatePgDBToolsFiles(genFormatted,exportStr);
			}			
		} else if ("DataDummy".equalsIgnoreCase(this.getSchema())) {
			generateDataDummyProjectFiles(ignoreWarning, genFormatted, genUi, genController, genService, genServiceImpl, genDao,
						genDaoImpl,exportStr);
		} else {		
			generateProjectFiles(ignoreWarning, genFormatted, genUi, genController, genService, genServiceImpl, genDao,
					genDaoImpl,generateExcel,exportStr);
		}
		ZipCompressor compressor = new ZipCompressor(this.folderPath+this.standardName+".zip");
		compressor.compressExe(this.getProjectFolderPath());
		delFolder(this.getProjectFolderPath());
	}
	
	public String getFolderPath() {
		return this.folderPath;
	}
	
	public String getProjectFolderPath(){
		if ( this.getStandardName()!= null && !"".equals(this.getStandardName())){
			return folderPath + this.getStandardName() + "/";
		}
		else return folderPath;
	}
	public void setFolderPath(String folderPath) {
		this.folderPath = folderPath;
	}
	
	public static String packagetokenToFolder(String packageToken){
		String folder = "";
		if (packageToken != null)
			 folder = packageToken.replace('.','/');
		folder += "/";
		return folder;
	}
	
	public static String folderToPackageToken(String folder){
		String packagetoken = folder.replace('/', '.');
		if (packagetoken.charAt(packagetoken.length()-1) == '.')
			packagetoken = packagetoken.substring(0, packagetoken.length() -1);
		return packagetoken;
	}
	public List<DBDefinitionGenerator> getDbDefinitionGenerators() {
		return dbDefinitionGenerators;
	}
	public void setDbDefinitionGenerators(
			List<DBDefinitionGenerator> dbDefinitionGenerators) {
		this.dbDefinitionGenerators = dbDefinitionGenerators;
	}
	
	public void addDBDefinitionGenerator(DBDefinitionGenerator generator){
		this.dbDefinitionGenerators.add(generator);
	}
	public String getDbName() {
		return dbName;
	}
	
	public void setDbName(String dbName) {
		this.dbName = dbName;		
	}	
	
	public TestSuite getProjectTestSuite() {
		return projectTestSuite;
	}
	public void setProjectTestSuite(TestSuite projectTestSuite) {
		this.projectTestSuite = projectTestSuite;
	}
	
	public void addTestSuite(TestSuite testSuite){
		this.projectTestSuite.testSuites.add(testSuite);
	}
	
	public void addTestCase(TestCase testCase){
		this.projectTestSuite.testCases.add(testCase);
	}
	
	public void addTestCases(List<TestCase> testCases){
		this.projectTestSuite.testCases.addAll(testCases);
	}
	public List<ConfigFile> getConfigFiles() {
		return configFiles;
	}
	public void setConfigFiles(List<ConfigFile> configFiles) {
		this.configFiles = configFiles;
	}
	
	public void addConfigFile(ConfigFile configFile){
		this.configFiles.add(configFile);
	}
	
	public void addConfigFiles(List<ConfigFile> configFiles){
		this.configFiles.addAll(configFiles);
	}
	
	public static void zipFile(File inFile, ZipOutputStream zos, String dir) throws IOException {
		if (inFile.isDirectory()) {
			File[] files = inFile.listFiles();
			for (File file:files)
				zipFile(file, zos, dir + "/" + inFile.getName());
		} else {
			String entryName = null;
			if (!"".equals(dir))
				entryName = dir + "/" + inFile.getName();
			else
				entryName = inFile.getName();
			ZipEntry entry = new ZipEntry(entryName);
			zos.putNextEntry(entry);
			InputStream is = new FileInputStream(inFile);
			int len = 0;
			while ((len = is.read()) != -1)
				zos.write(len);
			is.close();
		}
	}

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内�?
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文�?
				delFolder(path + "/" + tempList[i]);// 再删除空文件�?
				flag = true;
			}
		}
		return flag;
	}
	
	public ValidateInfo validate(){
		ValidateInfo info = new ValidateInfo();
		info.setSuccess(true);
		for (Domain d: this.domains){
			ValidateInfo v = d.validate();
			if (v.success(true) == false){
				info.setSuccess(false);
				info.addAllCompileErrors(v.getCompileErrors());
				info.addAllCompileWarnings(v.getCompileWarnings());
			}
		}
		for (Prism ps:this.prisms){
			ValidateInfo v = ps.validate(true);
			if (v.success(true) == false){
				info.setSuccess(false);
				info.addAllCompileErrors(v.getCompileErrors());
				info.addAllCompileWarnings(v.getCompileWarnings());
			}
		}
		return info;
	}
	public List<Domain> getDomains() {
		return domains;
	}
	public void setDomains(List<Domain> domains) {		
		for (Domain d: domains){
			this.addDomain(d);
		}
	}
	
	public void mergeDomains(List<Domain> domains) {	
		List<Domain> result = new ArrayList<Domain>();
		Set<Domain> set = new TreeSet<Domain>();
		set.addAll(this.domains);
		set.addAll(domains);
		result.addAll(set);
		this.domains = result;
	}
	
	public void addDomain(Domain domain){
		if (this.getDbPrefix() != null && !this.getDbPrefix().equals("")) {
			domain.setDbPrefix(this.getDbPrefix());	
		}
		this.domains.add(domain);
	}

	public String getDbPrefix() {
		return dbPrefix;
	}

	public void setDbPrefix(String dbPrefix) {
		this.dbPrefix = dbPrefix;
		for (Domain d:this.getDomains()){
			d.setDbPrefix(dbPrefix);
		}
		for (Prism p: this.getPrisms()){
			p.getDomain().setDbPrefix(dbPrefix);
		}
	
	}

	public String getTechnicalstack() {
		return technicalstack;
	}

	public void setTechnicalstack(String technicalstack) {
		this.technicalstack = technicalstack;
	}

	public String getDbUsername() {
		return dbUsername;
	}

	public void setDbUsername(String dbUsername) {
		this.dbUsername = dbUsername;
	}

	public String getDbPassword() {
		return dbPassword;
	}

	public void setDbPassword(String dbPassword) {
		this.dbPassword = dbPassword;
	}
	
	public void replaceConfigFile(ConfigFile cf){
		if (cf!=null && this.configFiles != null){
			if (this.configFiles.size()== 0 || !this.configFiles.contains(cf.getStandardName())) {
				this.configFiles.add(cf);
				return;
			}
			for (int i=0;i<this.configFiles.size();i++){
				if (this.configFiles.get(i).getStandardName().equals(cf.getStandardName())) {
					this.configFiles.remove(i);
					this.configFiles.add(cf);
				}
			}
		}
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getExcelTemplateName() {
		return excelTemplateName;
	}

	public void setExcelTemplateName(String excelTemplateName) {
		this.excelTemplateName = excelTemplateName;
	}

	public String getExcelTemplateFolder() {
		return excelTemplateFolder;
	}

	public void setExcelTemplateFolder(String excelTemplateFolder) {
		this.excelTemplateFolder = excelTemplateFolder;
	}
	
	public static File createPathFile(String path){
		try {
			File f = new File(path);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			f.createNewFile();
			return f;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public String getDbType() {
		return dbType;
	}

	public void setDbType(String dbType) {
		this.dbType = dbType;
	}
	
	public void addDataDomains(ArrayList<Domain> datas){
		this.dataDomains.add(datas);
	}

	public List<TwoDomainsDBDefinitionGenerator> getMyTwoDBGenerators() {
		return myTwoDBGenerators;
	}

	public void setMyTwoDBGenerators(List<TwoDomainsDBDefinitionGenerator> myTwoDBGenerators) {
		this.myTwoDBGenerators = myTwoDBGenerators;
	}
	
	public Nav decorateMentuItems() throws ValidateException{
		Set<ManyToMany> manyToManies = new TreeSet<ManyToMany>();
		for (Prism p : this.prisms) {
			manyToManies.addAll(p.getManyToManies());
		}
		Nav nav = new Nav();
		Set<Domain> navDomains = new TreeSet<>(new  DomainSerialComparator());
		navDomains.addAll(this.domains);
		nav.setDomains(navDomains);
		
		if (this.containsAuth()){
			SimpleAuthModule sam = (SimpleAuthModule) this.modules.get(0);
			String label = sam.getUserDomain().getText()+"资料";
			if ("english".equalsIgnoreCase(sam.getUserDomain().getLanguage())) {
				label = sam.getUserDomain().getText()+" Profile";
			}
			MenuItem profileMenu = new MenuItem("../pages/profile.html","Profile",label);
			nav.setProfileMenu(profileMenu);
		}
		
		for (ManyToMany mtm : manyToManies) {
			this.myTwoDBGenerators.add(mtm.toTwoDBGenerator());
		}

		Set<LayoutComb> layouts = new TreeSet<>();
		layouts.addAll(this.getLayoutCombs());
		nav.setLayouts(layouts);
		Set<ReportComb> reports = new TreeSet<>();
		reports.addAll(this.getReportCombs());
		nav.setReports(reports);
		nav.parse();
		return nav;
	}

	public List<List<Domain>> getDataDomains() {
		return dataDomains;
	}

	public void setDataDomains(List<List<Domain>> dataDomains) {
		this.dataDomains = dataDomains;
	}

	public Boolean getWithAuth() {
		return withAuth;
	}

	public void setWithAuth(Boolean withAuth) {
		this.withAuth = withAuth;
	}

	public String getModuleSourceFolderPath() {
		return moduleSourceFolderPath;
	}

	public void setModuleSourceFolderPath(String moduleSourceFolderPath) {
		this.moduleSourceFolderPath = moduleSourceFolderPath;
	}

	public List<DBUtil> getDbUtils() {
		return dbUtils;
	}

	public void setDbUtils(List<DBUtil> dbUtils) {
		this.dbUtils = dbUtils;
	}

	public void setPrisms(List<Prism> prisms) {
		this.prisms = prisms;
	}

	public String getDomainSuffix() {
		return domainSuffix;
	}

	public void setDomainSuffix(String domainSuffix) {
		this.domainSuffix = domainSuffix;
	}

	public String getDaoSuffix() {
		return daoSuffix;
	}

	public void setDaoSuffix(String daoSuffix) {
		this.daoSuffix = daoSuffix;
	}

	public String getDaoimplSuffix() {
		return daoimplSuffix;
	}

	public void setDaoimplSuffix(String daoimplSuffix) {
		this.daoimplSuffix = daoimplSuffix;
	}

	public String getServiceSuffix() {
		return serviceSuffix;
	}

	public void setServiceSuffix(String serviceSuffix) {
		this.serviceSuffix = serviceSuffix;
	}

	public String getServiceimplSuffix() {
		return serviceimplSuffix;
	}

	public void setServiceimplSuffix(String serviceimplSuffix) {
		this.serviceimplSuffix = serviceimplSuffix;
	}

	public String getControllerSuffix() {
		return controllerSuffix;
	}

	public void setControllerSuffix(String controllerSuffix) {
		this.controllerSuffix = controllerSuffix;
	}

	public String getDomainNamingSuffix() {
		return domainNamingSuffix;
	}

	public void setDomainNamingSuffix(String domainNamingSuffix) {
		this.domainNamingSuffix = domainNamingSuffix;
	}

	public String getControllerNamingSuffix() {
		return controllerNamingSuffix;
	}

	public void setControllerNamingSuffix(String controllerNamingSuffix) {
		this.controllerNamingSuffix = controllerNamingSuffix;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getSchema() {
		return schema;
	}

	public void setSchema(String schema) {
		this.schema = schema;
	}

	public String getFrontBaseApi() {
		return frontBaseApi;
	}

	public void setFrontBaseApi(String frontBaseApi) {
		this.frontBaseApi = frontBaseApi;
	}

	public List<org.light.core.Module> getModules() {
		return modules;
	}

	public void setModules(List<org.light.core.Module> modules) {
		this.modules = modules;
	}

	public List<LayoutComb> getLayoutCombs() {
		return layoutCombs;
	}

	public void setLayoutCombs(List<LayoutComb> layoutCombs) {
		this.layoutCombs = layoutCombs;
	}

	public List<ReportComb> getReportCombs() {
		return reportCombs;
	}

	public void setReportCombs(List<ReportComb> reportCombs) {
		this.reportCombs = reportCombs;
	}

	public Nav getNav() {
		return nav;
	}

	public void setNav(Nav nav) {
		this.nav = nav;
	}

	public boolean isSqlCommentsOn() {
		return sqlCommentsOn;
	}

	public void setSqlCommentsOn(boolean sqlCommentsOn) {
		this.sqlCommentsOn = sqlCommentsOn;
	}

	public String getComputerLanguage() {
		return computerLanguage;
	}

	public void setComputerLanguage(String computerLanguage) {
		this.computerLanguage = computerLanguage;
	}

	public String getOriginalExcelTemplateName() {
		return originalExcelTemplateName;
	}

	public void setOriginalExcelTemplateName(String originalExcelTemplateName) {
		this.originalExcelTemplateName = originalExcelTemplateName;
	}

	public String getFrontendUi() {
		return frontendUi;
	}

	public void setFrontendUi(String frontendUi) {
		this.frontendUi = frontendUi;
	}

	public String getBackendUi() {
		return backendUi;
	}

	public void setBackendUi(String backendUi) {
		this.backendUi = backendUi;
	}	
	
	public void setPureDbPrefix(String dbPrefix) {
		this.dbPrefix = dbPrefix;
	}
	
	public void addModule(org.light.core.Module m) {
		this.modules.add(m);
	}
	
	public boolean updateDomain(int pos, Domain domain) {
		if (this.domains != null && this.domains.size() == pos - 1) {
			this.domains.add(domain);
			return true;
		} else if (this.domains != null && this.domains.size() > pos) {
			this.domains.set(pos, domain);
			return true;
		}
		return false;
	}
	
	public void removeAllModules() {
		this.modules.clear();
	}
	
	
	public boolean clearLoginDataSimpleAuthModule() throws ValidateException{
		if (this.containsAuth()) {
			SimpleAuthModule sam = (SimpleAuthModule) this.modules.get(0);
			Domain userDomain = sam.getUserDomain();
			List<Domain> dcl = new ArrayList<>();
			for (Domain u : userDomain.getDummyDb()) {
				u.findFieldByFixedName("password").setFieldValue(u.findFieldByFixedName("userName").getFieldValue());
				u.findFieldByFixedName("loginFailure").setFieldValue("0");
				u.findFieldByFixedName("salt").setFieldValue("");
				dcl.add(u);
			}
			userDomain.setDummyDb(dcl);
			List<List<Domain>> finalDataDomainList = new ArrayList<>();
			for (List<Domain> ds : this.dataDomains) {
				Domain d1 = ds.get(0);
				if (d1.getStandardName().equals(userDomain.getStandardName())) {
					List<Domain> ddcl = new ArrayList<>();
					for (Domain u : ds) {
						u.findFieldByFixedName("password").setFieldValue(u.findFieldByFixedName("userName").getFieldValue());
						u.findFieldByFixedName("loginFailure").setFieldValue("0");
						u.findFieldByFixedName("salt").setFieldValue("");
						ddcl.add(u);
					}
					finalDataDomainList.add(ddcl);
				} else {
					finalDataDomainList.add(ds);
				}
				this.setDataDomains(finalDataDomainList);
				sam.setDataDomains(finalDataDomainList);
				sam.setUserDomain(userDomain);
			}
		} else {
			throw new ValidateException("没有登录模块！");
		}
		return false;
	}
	
	public boolean containsAuth() {
		if (this.getModules()!=null&& this.getModules().size()>0) {
			for (String mName:this.getModuleNames()) {
				if (mName.equalsIgnoreCase("SimpleAuth")) return true;
			}
		}
		return false;
	}
	
	public Set<String> getModuleNames() {
		Set<String> moduleNames = new TreeSet<>();
		for(org.light.core.Module m: this.modules) {
			moduleNames.add(m.getStandardName());
		}
		return moduleNames;
	}
	
	public void addLayoutComb(LayoutComb layoutComb) {
		this.layoutCombs.add(layoutComb);
	}
	
	public void addReportComb(ReportComb reportComb) {
		this.reportCombs.add(reportComb);
	}
	
	public void setReportComb(int pos,ReportComb report) {
		this.reportCombs.set(pos, report);
	}
	
	public void setLayoutComb(int pos,LayoutComb layoutComb) {
		this.layoutCombs.set(pos, layoutComb);
	}
	
	private void generateDataDummyProjectFiles(Boolean ignoreWarning, Boolean genFormatted, Boolean genUi,
			Boolean genController, Boolean genService, Boolean genServiceImpl, Boolean genDao, Boolean genDaoImpl,
			String exportStr) throws Exception {
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		ValidateInfo info = this.validate(ignoreWarning);
		if (info.success(ignoreWarning) == false) {
			throw new ValidateException(info);
		}
		decorateMentuItems();
		decorateProject();
		String srcfolderPath = this.getProjectFolderPath();
		for (Prism ps : this.prisms) {
			if (StringUtil.isBlank(exportStr) || exports.contains(ps.getDomain().getStandardName())){
				ps.setFolderPath(this.getProjectFolderPath());
				ps.generateDummyPrismFiles(ignoreWarning, genUi, genController, genService, genServiceImpl, genDao,
						genDaoImpl);
				for (ManyToMany mtm:ps.getManyToManies()) {
					EasyUIMtmPI mpage = mtm.getEuPI();
					mpage.setTechnicalStack(this.technicalstack);
					mpage.setTitles(this.getTitle(), this.getSubTitle(), this.getFooter());
					mpage.setNav(this.nav);
					mpage.generatePIFiles(srcfolderPath);
				}
			}
		}

		for (Util u:utils){
			String utilPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(u.getPackageToken()+".utils");
			String utilFilePath = utilPath+u.getFileName();
			writeToFile(utilFilePath, u.generateUtilString());
		}
		
		for (DBUtil du:dbUtils){
			String utilPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(du.getPackageToken()+".database");
			String utilFilePath = utilPath+du.getFileName();
			writeToFile(utilFilePath, du.generateUtilString());
		}
		
		for (SrcRootUtil sru:srcRootUtils){
			String utilPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sru.getPackageToken());
			String utilFilePath = utilPath+sru.getFileName();
			writeToFile(utilFilePath, sru.generateUtilString());
		}		
		
		for (org.light.core.Module m : this.modules) {
			if (StringUtil.isBlank(exportStr) || exports.contains(m.getStandardName())){
				m.generateDummyModuleFiles(this.getProjectFolderPath(),  genUi, genController,
						genService, genServiceImpl, genDao, genDaoImpl);
			}
		}
		
		for (LayoutComb lcb : this.layoutCombs) {
			if (StringUtil.isBlank(exportStr) || exports.contains(lcb.getStandardName())){
				lcb.generateCombFiles(this.getProjectFolderPath());
			}
		}
		
		for (ReportComb rcb : this.reportCombs) {
			if (StringUtil.isBlank(exportStr) || exports.contains(rcb.getStandardName())){
				rcb.generateCombFiles(this.getProjectFolderPath());
			}
		}
		
		Domain sampleDomain = this.getDomains().get(0);
		
		POMXml pomxml = new POMXml();
		pomxml.setSampleDomain(sampleDomain);
		pomxml.setContainsAuth(this.containsAuth());
		String pomFilePath = this.getProjectFolderPath() +pomxml.getFileName();
		writeToFile(pomFilePath,pomxml.generateStatementList().getContent());
		
		EasyUIHomePagePI homepage = new EasyUIHomePagePI(sampleDomain.getLanguage());
		homepage.setTitles(this.getTitle(),this.getSubTitle(),this.getFooter());
		homepage.setNav(this.getNav());
		homepage.generatePIFiles(this.getProjectFolderPath());

		DateUtilGenerator dug = new DateUtilGenerator();
		dug.setSampleDomain(sampleDomain);
		String dugPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
		String dugFilePath = dugPath+dug.getFileName();
		writeToFile(dugFilePath,dug.generateStatementList().getContent());

		JsonDateValueProcessorGenerator jdpg = new JsonDateValueProcessorGenerator();
		jdpg.setSampleDomain(sampleDomain);
		String jdpgPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
		String jdpgFilePath = jdpgPath+jdpg.getFileName();
		writeToFile(jdpgFilePath,jdpg.generateStatementList().getContent());

		JsonImageValueProcessorGenerator jipg = new JsonImageValueProcessorGenerator();
		jipg.setSampleDomain(sampleDomain);
		String jipgPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
		String jipgFilePath = jipgPath+jipg.getFileName();
		writeToFile(jipgFilePath,jipg.generateStatementList().getContent());

		ImageUtilGenerator iug = new ImageUtilGenerator();
		iug.setSampleDomain(sampleDomain);
		String iugPath = this.getProjectFolderPath() + "src/" + packagetokenToFolder(sampleDomain.getPackageToken())+"/utils/";
		String iugFilePath = iugPath+iug.getFileName();
		writeToFile(iugFilePath,iug.generateStatementList().getContent());

		JumpHomepageGenerator jhg = new JumpHomepageGenerator();
		jhg.setContainsAuth(this.containsAuth());
		String jhgPath = this.getProjectFolderPath() + "WebContent/";
		String jhgFilePath = jhgPath+jhg.getFileName();
		writeToFile(jhgFilePath,jhg.generateStatementList().getContent());

		String homePath = this.getProjectFolderPath() + "WebContent/";
//		if (genUi) {
//			if (this.containsLoginModule()) {
//				this.jumphomepage.setJumpFolder("login");
//			}
//			writeToFile(homePath + "index.html", this.jumphomepage.generateIncludeString());
//			String templateIndexFolder = this.getProjectFolderPath() + "src/main/resources/templates/";
//			writeToFile(templateIndexFolder + "index.html", this.jumphomepage.generateIncludeString());
//		}
//
//		if (genUi) {
//			this.homepage.generatePIFiles(this.getProjectFolderPath());
//		}
		
		FileCopyer copy = new FileCopyer();

		if (genUi) {
			File cssfrom = new File(this.getSourceFolderPath() + "css/");
			File cssto = new File(this.getProjectFolderPath() + "WebContent/css/");

			copy.dirFrom = cssfrom;
			copy.dirTo = cssto;
			copy.listFileInDir(cssfrom);

			File jsfrom = new File(this.getSourceFolderPath() + "js/");
			File jsto = new File(this.getProjectFolderPath() + "WebContent/js/");

			copy.dirFrom = jsfrom;
			copy.dirTo = jsto;
			copy.listFileInDir(jsfrom);

			File easyuifrom = new File(this.getSourceFolderPath() + "easyui/");
			File easyuito = new File(this.getProjectFolderPath() + "WebContent/easyui/");

			copy.dirFrom = easyuifrom;
			copy.dirTo = easyuito;
			copy.listFileInDir(easyuifrom);

			File uploadjsfrom = new File(this.getSourceFolderPath() + "uploadjs/");
			File uploadjsto = new File(this.getProjectFolderPath() + "WebContent/uploadjs/");

			copy.dirFrom = uploadjsfrom;
			copy.dirTo = uploadjsto;
			copy.listFileInDir(uploadjsfrom);
			
			File imagefrom = new File(this.getSourceFolderPath() + "images/");
			File imageto = new File(this.getProjectFolderPath() + "WebContent/images/");

			copy.dirFrom = imagefrom;
			copy.dirTo = imageto;
			copy.listFileInDir(imagefrom);
			
			File echartsfrom = new File(this.getSourceFolderPath() + "echarts/");
			File echartsto = new File(this.getProjectFolderPath() + "WebContent/echarts/");

			copy.dirFrom = echartsfrom;
			copy.dirTo = echartsto;
			copy.listFileInDir(echartsfrom);
		}

		copyExcelTemplates(genFormatted);

//		for (IndependentConfig idc : this.independentConfigs) {
//			writeToFile(this.getProjectFolderPath() + idc.getFolder() + idc.getFileName(),
//					idc.generateImplString());
//		}
	}
	
	public void copyExcelTemplates(boolean genFormatted) throws Exception{
		FileCopyer copy = new FileCopyer();
		if (!StringUtil.isBlank(this.getExcelTemplateName())) {
			File mF1 = new File(
					(this.getExcelTemplateFolder() + this.getExcelTemplateName()).replace("\\", "/"));
			File mF2 = new File(
					(this.getProjectFolderPath() + "exceltemplate/" + this.getExcelTemplateName())
							.replace("\\", "/"));
			if (mF1.exists()) {
				if (!mF2.getParentFile().exists()) {
					mF2.getParentFile().mkdirs();
				}
				if (!mF2.exists()) {
					mF2.createNewFile();
				}
				copy.copy(mF1.getPath(), mF2.getPath());
			}
			if (!StringUtil.isBlank(this.getOriginalExcelTemplateName())) {
				File mF3 = new File(
						(this.getExcelTemplateFolder() + this.getOriginalExcelTemplateName()).replace("\\", "/"));
				File mF4 = new File(
						(this.getProjectFolderPath() + "exceltemplate/" + this.getOriginalExcelTemplateName())
								.replace("\\", "/"));
				if (mF3.exists()) {
					if (!mF4.getParentFile().exists()) {
						mF4.getParentFile().mkdirs();
					}
					if (!mF4.exists()) {
						mF4.createNewFile();
					}
					copy.copy(mF3.getPath(), mF4.getPath());
				}
			}
			if (genFormatted && StringUtil.isBlank(this.originalExcelTemplateName)) {
				String genExcelFile = "Gen_formatted";
				String[] genExcelFiles = this.getExcelTemplateName().split("\\.");
				if (genExcelFiles != null && genExcelFiles.length > 0)
					genExcelFile = genExcelFiles[0] + "_formatted";
				ExcelWizard.outputExcelWorkBook(this,
						(this.getProjectFolderPath() + "exceltemplate/").replace("\\", "/"),
						genExcelFile + ".xls");
			}
		}
	}

	private boolean containsLoginModule() {
		Set<String> moduleNames = this.getModuleNames();
		if (moduleNames.contains("SimpleAuth")) return true;
		else return false;
	}
	
	public ValidateInfo validate(Boolean ignoreWarning) {
		ValidateInfo info = new ValidateInfo();
		for (Domain d : this.domains) {
			ValidateInfo v = d.validate(this.getDbType());
			if (v.success(ignoreWarning) == false) {
				info.setSuccess(false);
				info.addAllCompileErrors(v.getCompileErrors());
				info.addAllCompileWarnings(v.getCompileWarnings());
			}
		}
		for (Prism ps : this.prisms) {
			ValidateInfo v = ps.validate(ignoreWarning);
			info.addAllCompileErrors(v.getCompileErrors());
			info.addAllCompileWarnings(v.getCompileWarnings());
		}
		return info;
	}

	public void generateMariaDBToolsFiles(boolean genFormatted,String exportStr) throws Exception {
		decorateMentuItems();
		
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		
		StringBuilder sql = new StringBuilder();
		boolean createNew = true;
		for (DBDefinitionGenerator dbd : dbDefinitionGenerators) {
			sql.append(dbd.generateDBSql(createNew, this.sqlCommentsOn,exportStr)).append("\n");
			if (createNew)
				createNew = false;
		}
		for (TwoDomainsDBDefinitionGenerator mtg : this.getMyTwoDBGenerators()) {
			sql.append(mtg.generateDBSql(this.getDbType(),this.sqlCommentsOn,exportStr));
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						sql.append(SqlReflector.generateInsertSqlWithValue(d)).append("\n");
					}
				}
			}

			for (Domain d : dataDomains) {
				for (ManyToMany mtm : d.getManyToManies()) {
					if (StringUtil.isBlank(exportStr)||exports.contains(mtm.getMaster().getStandardName())) {
						sql.append(SqlReflector.generateMtmInsertSqlWithValues(mtm)).append("\n");
					}
				}
			}
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						if (d.hasDomainId()) {
							sql.append(SqlReflector.generateUpdateSqlWithValue(d)).append("\n");
						}
					}
				}
			}
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						if (d.hasDomainId())
							sql.append(SqlReflector.generateDeleteSqlWithValue(d)).append("\n");
					}
				}
			}

			for (Domain d : dataDomains) {
				for (ManyToMany mtm : d.getManyToManies()) {
					if (StringUtil.isBlank(exportStr)||exports.contains(mtm.getMaster().getStandardName())) {
						sql.append(SqlReflector.generateMtmDeleteSqlWithValues(mtm)).append("\n");
					}
				}
			}
		}

		sql.append("\n");
		for (DBDefinitionGenerator dbd : dbDefinitionGenerators) {
			sql.append(dbd.generateDropTableSqls(false,exportStr)).append("\n");
		}

		for (TwoDomainsDBDefinitionGenerator mtg : this.getMyTwoDBGenerators()) {
			if (StringUtil.isBlank(exportStr)||exports.contains(mtg.getMaster().getStandardName())) {
				sql.append(mtg.generateDropLinkTableSql());
			}
		}

		writeToFile(this.getProjectFolderPath() + "sql/" + this.getStandardName() + ".sql", sql.toString());
		copyExcelTemplates(genFormatted);
	}

	public void generateOracleDBToolsFiles(boolean genFormatted,String exportStr) throws Exception {
		decorateMentuItems();
		
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		
		StringBuilder sql = new StringBuilder();
		boolean createNew = false;
		for (DBDefinitionGenerator dbd : dbDefinitionGenerators) {
			sql.append(dbd.generateDropTableSqls(createNew,exportStr));
		}
		
		for (TwoDomainsDBDefinitionGenerator mtg : this.myTwoDBGenerators) {
			OracleTwoDomainsDBDefinitionGenerator otg = OracleTwoDomainsDBDefinitionGenerator.toOracleTwoDomainsDBDefinitionGenerator(mtg);
			if (StringUtil.isBlank(exportStr)||exports.contains(otg.getMaster().getStandardName())) {
				sql.append(otg.generateDropLinkTableSql());
			}
		}

		sql.append("\n\n");

		sql.append("drop sequence COMMONSEQUENCE;").append("\n\n");
		sql.append("-- Create sequence").append("\n").append("create sequence COMMONSEQUENCE").append("\n")
				.append("minvalue 10000").append("\n").append("maxvalue 9999999999999999999999999999").append("\n")
				.append("start with 10000").append("\n").append("increment by 1").append("\n").append("cache 20;")
				.append("\n\n");

		for (DBDefinitionGenerator dbd : dbDefinitionGenerators) {
			sql.append(dbd.generateDBSql(createNew,this.sqlCommentsOn,exportStr)).append("\n");
		}
		for (TwoDomainsDBDefinitionGenerator mtg : this.myTwoDBGenerators) {
			sql.append(mtg.generateDBSql(this.getDbType(),this.sqlCommentsOn,exportStr));
		}

		// load initial data
		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						sql.append(Oracle11gSqlReflector.generateInsertSqlWithValue(d)).append("\n");
					}
				}
			}

			for (Domain d : dataDomains) {
				for (ManyToMany mtm : d.getManyToManies()) {
					if (StringUtil.isBlank(exportStr)||exports.contains(mtm.getMaster().getStandardName())) {
						sql.append(Oracle11gSqlReflector.generateMtmInsertSqlWithValues(mtm)).append("\n");
					}
				}
			}
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						sql.append(Oracle11gSqlReflector.generateUpdateSqlWithValue(d)).append("\n");
					}
				}
			}
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						sql.append(Oracle11gSqlReflector.generateDeleteSqlWithValue(d)).append("\n");
					}
				}
			}

			for (Domain d : dataDomains) {
				for (ManyToMany mtm : d.getManyToManies()) {
					if (StringUtil.isBlank(exportStr)||exports.contains(mtm.getMaster().getStandardName())) {
						sql.append(SqlReflector.generateMtmDeleteSqlWithValues(mtm)).append("\n");
					}
				}
			}
		}

		sql.append("commit;\n");
		writeToFile(this.getProjectFolderPath() + "sql/" + this.standardName + ".sql", sql.toString());

		copyExcelTemplates(genFormatted);
	}

	public void generatePgDBToolsFiles(boolean genFormatted, String exportStr) throws Exception {
		decorateMentuItems();
		
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		
		StringBuilder sql = new StringBuilder();
		boolean createNew = true;
		for (DBDefinitionGenerator dbd : dbDefinitionGenerators) {
			sql.append(dbd.generateDBSql(createNew,this.sqlCommentsOn,exportStr)).append("\n");
			if (createNew)
				createNew = false;
		}
		for (TwoDomainsDBDefinitionGenerator mtg : this.getMyTwoDBGenerators()) {
			sql.append(mtg.generateDBSql(this.getDbType(),this.sqlCommentsOn,exportStr));
		}

		sql.append("\n");
		for (Domain d : getDomains()) {
			if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
				if (!(d instanceof org.light.domain.Enum)) {
					sql.append(PgsqlReflector.generateSetSerialVal10000(d)).append("\n");
				}
			}
		}
		sql.append("\n");

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						sql.append(PgsqlReflector.generateInsertSqlWithValue(d)).append("\n");
					}
				}
			}

			for (Domain d : dataDomains) {
				for (ManyToMany mtm : d.getManyToManies()) {
					if (StringUtil.isBlank(exportStr)||exports.contains(mtm.getMaster().getStandardName())) {
						sql.append(PgsqlReflector.generateMtmInsertSqlWithValues(mtm)).append("\n");
					}
				}
			}
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						if (d.hasDomainId())
							sql.append(PgsqlReflector.generateUpdateSqlWithValue(d)).append("\n");
					}
				}
			}
		}

		for (List<Domain> dataDomains : this.getDataDomains()) {
			sql.append("\n");
			for (Domain d : dataDomains) {
				if (StringUtil.isBlank(exportStr)||exports.contains(d.getStandardName())) {
					if (!(d instanceof org.light.domain.Enum)) {
						if (d.hasDomainId())
							sql.append(PgsqlReflector.generateDeleteSqlWithValue(d)).append("\n");
					}
				}
			}

			for (Domain d : dataDomains) {
				for (ManyToMany mtm : d.getManyToManies()) {
					if (StringUtil.isBlank(exportStr)||exports.contains(mtm.getMaster().getStandardName())) {
						sql.append(PgsqlReflector.generateMtmDeleteSqlWithValues(mtm)).append("\n");
					}
				}
			}
		}

		sql.append("\n");
		for (DBDefinitionGenerator dbd : dbDefinitionGenerators) {
			sql.append(dbd.generateDropTableSqls(false,exportStr)).append("\n");
		}

		for (TwoDomainsDBDefinitionGenerator mtg : this.getMyTwoDBGenerators()) {
			if (StringUtil.isBlank(exportStr)||exports.contains(mtg.getMaster().getStandardName())) {
				sql.append(mtg.generateDropLinkTableSql());
			}
		}

		writeToFile(this.getProjectFolderPath() + "sql/" + this.getStandardName() + ".sql", sql.toString());
		copyExcelTemplates(genFormatted);
	}
}
